#include "TelegrafLib.h"


// ==================== 构造函数和析构函数 ====================

// 构造函数 - 必须实现
DBConfig::DBConfig(const std::string& filename) : db_connection_(NULL), query_timeout_(30) 
{
		load(filename);
}

// 析构函数 - 必须实现
DBConfig::~DBConfig() 
{
	disconnectFromDB();
}

// ==================== 原有的所有函数实现 ====================

size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) 
{
	((std::string*)userp)->append((char*)contents, size * nmemb);
	return size * nmemb;
}

std::string loginAndGetToken(const std::string& url, const std::string& auth) 
{
	CURL* curl;
	CURLcode res;
	std::string response;
	curl_global_init(CURL_GLOBAL_DEFAULT);
	curl = curl_easy_init();
	if (curl) 
	{
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		struct curl_slist* headers = NULL;
		headers = curl_slist_append(headers, ("Authorization: " + auth).c_str());
		headers = curl_slist_append(headers, "Content-Type: text/plain");
		headers = curl_slist_append(headers, "Accept: application/json");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
		res = curl_easy_perform(curl);
		if (res != CURLE_OK) 
		{
			std::cerr << "Request failed: " << curl_easy_strerror(res) << std::endl;
			response.clear();
		}
		curl_easy_cleanup(curl);
		curl_slist_free_all(headers);
	}
	curl_global_cleanup();
	return response;
}

std::string extractToken(const std::string& response) 
{
	size_t pos = response.find("\"token\":\"");
	if (pos != std::string::npos) 
	{
		pos += 9;
		size_t endPos = response.find("\"", pos);
		if (endPos != std::string::npos) 
		{
			return response.substr(pos, endPos - pos);
		}
	}
	return "";
}

int insertDataWithToken(const std::string& url, const std::string& postData, const std::string& token) 
{
	CURL* curl;
	CURLcode res;
	std::string response;
	curl_global_init(CURL_GLOBAL_DEFAULT);
	curl = curl_easy_init();
	if (curl) 
	{
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		struct curl_slist* headers = NULL;
		headers = curl_slist_append(headers, ("Authorization: " + token).c_str());
		headers = curl_slist_append(headers, "Content-Type: text/plain");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		// 暂时禁用 SSL 证书验证  TODO后续最好加上证书
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);  // 禁用对等验证
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);  // 禁用主机验证
		// 设置 POST 数据
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.c_str());

		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
		res = curl_easy_perform(curl);
		if (res != CURLE_OK) 
		{
			std::cerr << "Request failed: " << curl_easy_strerror(res) << std::endl;
		} 
		else 
		{
			std::cout << "Insert response: " << response << std::endl;
		}
		curl_easy_cleanup(curl);
		curl_slist_free_all(headers);
	}
	curl_global_cleanup();
	return res;
}

std::string base64_encode(const std::string& bytes_to_encode)
{
	std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	std::string ret;
	int i = 0;
	unsigned char char_array_3[3];
	unsigned char char_array_4[4];
	const char* bytes = bytes_to_encode.c_str();
	int len = (int)bytes_to_encode.length();
	int pos = 0;
	while (len--) 
	{
		char_array_3[i++] = bytes[pos++];
		if (i == 3) 
		{
			char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
			char_array_4[1] = ((char_array_3[0] & 0x03) << 4) |
				((char_array_3[1] & 0xf0) >> 4);
			char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) |
				((char_array_3[2] & 0xc0) >> 6);
			char_array_4[3] = char_array_3[2] & 0x3f;
			for (i = 0; i < 4; i++)
				ret += base64_chars[char_array_4[i]];
			i = 0;
		}
	}
	if (i > 0) 
	{
		for (int j = i; j < 3; j++)
			char_array_3[j] = '\0';
		char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
		char_array_4[1] = ((char_array_3[0] & 0x03) << 4) |
			((char_array_3[1] & 0xf0) >> 4);
		char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) |
			((char_array_3[2] & 0xc0) >> 6);
		char_array_4[3] = char_array_3[2] & 0x3f;
		for (int j = 0; j < i + 1; j++)
			ret += base64_chars[char_array_4[j]];
		while (i++ < 3)
			ret += '=';
	}
	return ret;
}

std::string DBConfig::getbase64()
{
	std::string user_password = data.user + ":" + data.password ;
	std::string getbase64 = base64_encode(user_password);
	std::string auth = "Basic " + getbase64; // Base64 编码后的 "root:root123"
	return auth;
}

void DBConfig::load(const std::string& filename) 
{
	std::ifstream file(filename);
	if (!file.is_open()) 
	{
		std::cerr << "未找到配置文件 " << filename<< "，将使用默认配置。\n";
		return;
	}
	std::string line;
	while (std::getline(file, line)) 
	{
		if (line.empty() || line[0] == '#')
			continue;
		std::stringstream ss(line);
		std::string token;
		std::vector<std::string> fields;
		while (std::getline(ss, token, ':')) 
		{
			fields.push_back(token);
		}
		if (fields.size() < 7) 
		{
			std::cerr << "[警告] 配置字段不足，使用默认值。\n";
			return;
		}
		data.ip = fields[0];
		data.dbPort = fields[1];
		data.httpPort = fields[2];
		data.user = fields[3];
		data.password = fields[4];
		data.defaultDB = fields[5];
		data.hisDB = fields[6];
		break;  // 只读第一条配置
	}
	file.close();
}

void DBConfig::print() const 
{
	std::cout << "主机IP: " << data.ip << std::endl;
	std::cout << "数据库端口: " << data.dbPort << std::endl;
	std::cout << "HTTP端口: " << data.httpPort << std::endl;
	std::cout << "用户名: " << data.user << std::endl;
	std::cout << "密码: " << data.password << std::endl;
	std::cout << "默认关系库: " << data.defaultDB << std::endl;
	std::cout << "默认时序库: " << data.hisDB << std::endl;
}

//用于时序库插入前先登录
int DBConfig::login() 
{
	std::string loginUrl = "https://" + data.ip + ":" + data.httpPort + "/restapi/login";
	std::string base64_user = getbase64();
	std::string loginResponse = loginAndGetToken(loginUrl, base64_user);
	if (loginResponse.empty()) 
		return DBCI_ERROR;  // 登录失败
	std::string token = extractToken(loginResponse);
	return (token.empty() ? DBCIERR_CONNECT_FAIL : DBCI_OK); 
}

//telegraf line protocol格式的数据写入时序库 mode==0自动建表
int DBConfig::insert(const std::string& postData,int mode) 
{
	std::string base64_user = getbase64();
	std::string insertUrl = "https://" + data.ip + ":" + data.httpPort + "/restapi/";
	if (1 == mode)//手动建表
	{
		insertUrl = insertUrl + "telegraf?db=" + data.hisDB;
	}
	else //自动建表
	{
		insertUrl = insertUrl + "influxdb?db=" + data.hisDB;
	}
	int ret = insertDataWithToken(insertUrl, postData, base64_user);
	return (ret ? DBCIERR_INSERT_FAIL : DBCI_OK); 
}



// ==================== 关系数据库接口实现 ====================
//初始化连接
DBConfig::ConnectionStatus DBConfig::connectInitDB(const std::string& database) 
{
	std::string db_name = database.empty() ? data.defaultDB : database;
	std::ostringstream conn_str;
	conn_str << "host=" << data.ip << " port=" << data.dbPort << " dbname=" << db_name << " user=" << data.user << " password=" << data.password;
	db_connection_ = PQconnectdb(conn_str.str().c_str());
	if (PQstatus(db_connection_) == CONNECTION_OK) 
	{
		std::ostringstream timeout_oss;
		timeout_oss << "SET statement_timeout = " << (query_timeout_ * 1000);
		PGresult* res = PQexec(db_connection_, timeout_oss.str().c_str());
		PQclear(res);
		return CONNECTION_OK;
	} 
	else 
	{
		last_error_ = PQerrorMessage(db_connection_);
		PQfinish(db_connection_); db_connection_ = NULL;
		return CONNECTION_FAILED;
	}
}
//断开连接
void DBConfig::disconnectFromDB() 
{
	if (db_connection_) 
	{
		PQfinish(db_connection_);
		db_connection_ = NULL;
	}
}
//检查是否连接正常
bool DBConfig::isDBConnected() const 
{
	return db_connection_ && PQstatus(db_connection_) == CONNECTION_OK;
}
//创建数据库
bool DBConfig::createDatabase(const std::string& db_name) 
{
	std::string db = db_name.empty() ? data.defaultDB : db_name;
	std::string sql = "CREATE DATABASE " + escapeString(db);
	return executeCommand(sql);
}
//选中数据库
bool DBConfig::useDatabase(const std::string& db_name) 
{
	std::string db = db_name.empty() ? data.defaultDB : db_name;
	std::string sql = "USE " + escapeString(db);
	return executeCommand(sql);
}
//表是否存在
bool DBConfig::tableExists(const std::string& table_name) 
{
	QueryResult result = executeQuery("SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = '" + table_name + "')");

	if (result.success && !result.rows.empty()) 
	{
		return result.rows[0]["exists"] == "t";
	}
	return false;
}
//创建表
bool DBConfig::createTable(const std::string& table_name, const std::vector<std::string>& columns,const std::string& primary_key) 
{
	if (columns.empty()) 
	{
		last_error_ = "No columns specified for table creation";
		return false;
	}
	std::ostringstream sql;
	sql << "CREATE TABLE " << escapeString(table_name) << " (";
	for (size_t i = 0; i < columns.size(); ++i) 
	{
		if (i > 0) sql << ", ";
		sql << escapeString(columns[i]) << " TEXT";
	}
	if (!primary_key.empty()) 
	{
		sql << ", PRIMARY KEY (" << escapeString(primary_key) << ")";
	}
	sql << ")";
	return executeCommand(sql.str());
}
//创建不存在的表，已存在则跳过
bool DBConfig::createTableIfNotExists(const std::string& table_name,const std::vector<std::string>& columns,const std::string& primary_key) 
{
	// 先检查表是否已经存在
	if (tableExists(table_name)) 
	{
		std::cout << "表 '" << table_name << "' 已存在，跳过创建" << std::endl;
		return true;  // 表已存在
	}
	return createTable(table_name, columns, primary_key);
}
//删除表
bool DBConfig::dropTable(const std::string& table_name) 
{
	std::string sql = "DROP TABLE IF EXISTS " + escapeString(table_name);
	return executeCommand(sql);
}
//insert插入
bool DBConfig::insertToDB(const std::string& table_name, const std::map<std::string, std::string>& data) 
{
	if (data.empty()) 
	{
		last_error_ = "No data to insert";
		return false;
	}
	std::ostringstream sql, columns, values;
	sql << "INSERT INTO " << escapeString(table_name) << " (";
	size_t count = 0;
	for (std::map<std::string, std::string>::const_iterator it = data.begin();it != data.end(); ++it) 
	{
		if (count > 0) 
		{
			columns << ", ";
			values << ", ";
		}
		columns << escapeString(it->first);
		values << "'" << it->second << "'";
		count++;
	}
	sql << columns.str() << ") VALUES (" << values.str() << ")";
	return executeCommand(sql.str());
}
//COPY快速插入
bool DBConfig::batchInsertToDB(const std::string& table_name, const std::vector<std::map<std::string, std::string> >& data_list) 
{
	if (data_list.empty()) return true;
	const int MAX_BATCH_SIZE = 100000; // 每批最大记录数
	//
	// TODO 
	//后续优化 根据获取计算机可用内存的1/4大小来决定最大记录数
	// 
	if (data_list.size() <= MAX_BATCH_SIZE) 
	{
		return batchInsertSingleBatch(table_name, data_list);
	}
	std::cout << "=== 大数据量分批插入 ===" << std::endl;
	std::cout << "总记录数: " << data_list.size() << std::endl;
	std::cout << "批次大小: " << MAX_BATCH_SIZE << std::endl;
	std::cout << "预计批次: " << ((data_list.size() + MAX_BATCH_SIZE - 1) / MAX_BATCH_SIZE) << std::endl;
	int total_success = 0;
	auto total_start = std::clock();
	for (size_t start = 0; start < data_list.size(); start += MAX_BATCH_SIZE) 
	{
		size_t end = start + MAX_BATCH_SIZE;
		if (end > data_list.size())
			end = data_list.size();
		int current_batch = (start / MAX_BATCH_SIZE) + 1;
		int total_batches = (data_list.size() + MAX_BATCH_SIZE - 1) / MAX_BATCH_SIZE;
		std::cout << "\n--- 处理批次 " << current_batch << "/" << total_batches 
			<< " (" << start << "-" << (end-1) << ") ---" << std::endl;
		// 提取当前批次数据
		std::vector<std::map<std::string, std::string>> batch_data(data_list.begin() + start, data_list.begin() + end);
		auto batch_start = std::clock();
		if (batchInsertSingleBatch(table_name, batch_data)) 
		{
			auto batch_end = std::clock();
			double batch_duration = double(batch_end - batch_start) / CLOCKS_PER_SEC;
			total_success += batch_data.size();
			std::cout << "批次 " << current_batch << " 成功: " << batch_data.size() 
				<< " 条记录, 耗时: " << std::fixed << std::setprecision(3) 
				<< batch_duration << " 秒" 
				<< " (" << std::setprecision(1) << (batch_data.size() / batch_duration) << " 条/秒)" << std::endl;
		} 
		else 
		{
			std::cout << "批次 " << current_batch << " 失败: " << getLastError() << std::endl;
			return false;
		}
	}
	auto total_end = std::clock();
	double total_duration = double(total_end - total_start) / CLOCKS_PER_SEC;
	std::cout << "\n=== 分批插入完成 ===" << std::endl;
	std::cout << "总成功记录: " << total_success << "/" << data_list.size() << std::endl;
	std::cout << "总耗时: " << std::fixed << std::setprecision(3) << total_duration << " 秒" << std::endl;
	std::cout << "平均速度: " << std::setprecision(1) << (total_success / total_duration) << " 条/秒" << std::endl;
	return (total_success == data_list.size());
}
// 分批次插入
bool DBConfig::batchInsertSingleBatch(const std::string& table_name, const std::vector<std::map<std::string, std::string> >& data_list) 
{
	if (data_list.empty()) return true;
	if (data_list[0].empty()) 
	{
		last_error_ = "No data columns available";
		return false;
	}
	std::ostringstream copy_cmd;
	copy_cmd << "COPY " << escapeString(table_name) << " (";
	bool first_col = true;
	for (std::map<std::string, std::string>::const_iterator it = data_list[0].begin();it != data_list[0].end(); ++it) 
	{
		if (!first_col) copy_cmd << ", ";
		copy_cmd << escapeString(it->first);
		first_col = false;
	}
	copy_cmd << ") FROM STDIN";

	PGresult* res = PQexec(db_connection_, copy_cmd.str().c_str());
	if (PQresultStatus(res) != PGRES_COPY_IN) 
	{
		last_error_ = PQerrorMessage(db_connection_);
		PQclear(res);
		return false;
	}
	PQclear(res);
	std::ostringstream full_data;
	for (size_t i = 0; i < data_list.size(); ++i) 
	{
		const std::map<std::string, std::string>& row = data_list[i];
		bool first_field = true;
		for (std::map<std::string, std::string>::const_iterator it = row.begin();it != row.end(); ++it) 
		{
			if (!first_field) full_data << "\t";
			full_data << it->second;
			first_field = false;
		}
		full_data << "\n";
	}
	std::string all_data = full_data.str();
	int copy_result = PQputCopyData(db_connection_, all_data.c_str(), all_data.length());
	if (copy_result != 1) 
	{
		last_error_ = PQerrorMessage(db_connection_);
		PQputCopyEnd(db_connection_, last_error_.c_str());
		return false;
	}
	if (PQputCopyEnd(db_connection_, NULL) != 1) 
	{
		last_error_ = PQerrorMessage(db_connection_);
		return false;
	}
	res = PQgetResult(db_connection_);
	bool success = (PQresultStatus(res) == PGRES_COMMAND_OK);
	if (!success) last_error_ = PQerrorMessage(db_connection_);
	PQclear(res);

	return success;
}
//执行sql语句 有返回数据的查询
QueryResult DBConfig::executeQuery(const std::string& sql) 
{
	QueryResult result;
	if (!checkConnection()) 
	{
		result.error_message = "Not connected to database";
		return result;
	}
	PGresult* res = PQexec(db_connection_, sql.c_str());
	if (PQresultStatus(res) != PGRES_TUPLES_OK) 
	{
		result.error_message = PQerrorMessage(db_connection_);
		PQclear(res);
		return result;
	}
	// 列信息
	result.column_count = PQnfields(res);
	for (int i = 0; i < result.column_count; i++) 
	{
		result.columns.push_back(PQfname(res, i));
	}
	// 行数据
	result.row_count = PQntuples(res);
	for (int i = 0; i < result.row_count; i++) 
	{
		std::map<std::string, std::string> row;
		for (int j = 0; j < result.column_count; j++) 
		{
			const char* value = PQgetvalue(res, i, j);
			row[result.columns[j]] = value ? value : "";
		}
		result.rows.push_back(row);
	}
	result.success = true;
	PQclear(res);
	return result;
}
//查询  参数列表：表名，列名，限制条件，排序，限制条数
QueryResult DBConfig::selectFromDB(const std::string& table_name,const std::vector<std::string>& columns,const std::string& where_clause,const std::string& order_by,int limit) 
{
	std::ostringstream sql;
	sql << "SELECT ";
	if (columns.empty()) 
	{
		sql << "*";
	} 
	else 
	{
		for (size_t i = 0; i < columns.size(); ++i) 
		{
			if (i > 0) sql << ", ";
			sql << escapeString(columns[i]);
		}
	}
	sql << " FROM " << escapeString(table_name);
	if (!where_clause.empty()) 
	{
		sql << " WHERE " << where_clause;
	}
	if (!order_by.empty()) 
	{
		sql << " ORDER BY " << order_by;
	}
	if (limit > 0) 
	{
		sql << " LIMIT " << intToString(limit);
	}
	return executeQuery(sql.str());
}
//执行sql语句 无数据返回
bool DBConfig::executeCommand(const std::string& sql) 
{
	if (!checkConnection()) 
	{
		last_error_ = "Not connected to database";
		return false;
	}
	PGresult* res = PQexec(db_connection_, sql.c_str());
	bool success = (PQresultStatus(res) == PGRES_COMMAND_OK);
	if (!success) 
	{
		last_error_ = PQerrorMessage(db_connection_);
	}
	PQclear(res);
	return success;
}
//获取表中记录数量
int DBConfig::getRowCount(const std::string& table_name, const std::string& where_clause) 
{
	std::string sql = "SELECT COUNT(*) as count FROM " + escapeString(table_name);
	if (!where_clause.empty()) 
	{
		sql += " WHERE " + where_clause;
	}
	QueryResult result = executeQuery(sql);
	if (result.success && !result.rows.empty()) 
	{
		return atoi(result.rows[0]["count"].c_str());
	}
	return DBCI_ERROR;
}

// ==================== 其他函数 ====================

std::string DBConfig::getLastError() const 
{
	return last_error_;
}

void DBConfig::setQueryTimeout(int seconds) 
{
	query_timeout_ = seconds;
	if (db_connection_) 
	{
		std::ostringstream timeout_oss;
		timeout_oss << "SET statement_timeout = " << (query_timeout_ * 1000);
		PGresult* res = PQexec(db_connection_, timeout_oss.str().c_str());
		PQclear(res);
	}
}

std::string DBConfig::intToString(int value) 
{
	std::ostringstream oss;
	oss << value;
	return oss.str();
}

std::string DBConfig::doubleToString(double value) 
{
	std::ostringstream oss;
	oss << std::fixed << value;
	return oss.str();
}

std::string DBConfig::escapeString(const std::string& str) 
{
	if (!db_connection_) return str;
	char* escaped = PQescapeIdentifier(db_connection_, str.c_str(), str.length());
	if (escaped) 
	{
		std::string result(escaped);
		PQfreemem(escaped);
		return result;
	}
	return str;
}

std::string DBConfig::escapeLiteral(const std::string& str) 
{
	if (!db_connection_) return "'" + str + "'";
	char* escaped = PQescapeLiteral(db_connection_, str.c_str(), str.length());
	if (escaped) 
	{
		std::string result(escaped);
		PQfreemem(escaped);
		return result;
	}
	return "'" + str + "'";
}

bool DBConfig::checkConnection() 
{
	if (!isDBConnected()) 
	{
		last_error_ = "Not connected to database";
		return false;
	}
	return true;
}

// ==================== JNI接口实现 ====================

#ifdef TELEGRAF_JNI_EXPORT

#include <jni.h>

// 辅助函数：jstring 转 std::string
std::string jstringToString(JNIEnv* env, jstring jstr) {
	if (!jstr) return "";

	const char* chars = env->GetStringUTFChars(jstr, NULL);
	std::string result(chars);
	env->ReleaseStringUTFChars(jstr, chars);

	return result;
}

// 辅助函数：std::string 转 jstring
jstring stringToJString(JNIEnv* env, const std::string& str) {
	return env->NewStringUTF(str.c_str());
}

// 辅助函数：Java String[] 转 std::vector<std::string>
std::vector<std::string> jobjectArrayToStringVector(JNIEnv* env, jobjectArray jarray) {
	std::vector<std::string> result;

	if (!jarray) return result;

	jsize length = env->GetArrayLength(jarray);
	for (jsize i = 0; i < length; i++) {
		jstring jstr = (jstring)env->GetObjectArrayElement(jarray, i);
		result.push_back(jstringToString(env, jstr));
		env->DeleteLocalRef(jstr);
	}

	return result;
}

// 辅助函数：JSON字符串转map（简单实现）
std::map<std::string, std::string> jsonStringToMap(const std::string& jsonStr) {
	std::map<std::string, std::string> result;
	if (jsonStr.length() < 3) return result;

	// 移除外层花括号
	std::string content = jsonStr.substr(1, jsonStr.length() - 2);

	size_t pos = 0;
	while (pos < content.length()) {
		// 查找键
		size_t keyStart = content.find('"', pos);
		if (keyStart == std::string::npos) break;
		size_t keyEnd = content.find('"', keyStart + 1);
		if (keyEnd == std::string::npos) break;

		std::string key = content.substr(keyStart + 1, keyEnd - keyStart - 1);

		// 查找值
		size_t valueStart = content.find('"', keyEnd + 1);
		if (valueStart == std::string::npos) break;
		size_t valueEnd = content.find('"', valueStart + 1);
		if (valueEnd == std::string::npos) break;

		std::string value = content.substr(valueStart + 1, valueEnd - valueStart - 1);

		result[key] = value;
		pos = valueEnd + 1;
	}

	return result;
}

// 辅助函数：QueryResult转JSON字符串
std::string queryResultToJson(const QueryResult& result) {
	std::ostringstream json;
	json << "{";
	json << "\"success\":" << (result.success ? "true" : "false") << ",";
	json << "\"error_message\":\"" << result.error_message << "\",";
	json << "\"row_count\":" << result.row_count << ",";
	json << "\"column_count\":" << result.column_count << ",";

	// 列信息
	json << "\"columns\":[";
	for (size_t i = 0; i < result.columns.size(); i++) {
		if (i > 0) json << ",";
		json << "\"" << result.columns[i] << "\"";
	}
	json << "],";

	// 行数据 - 使用传统迭代器替代auto
	json << "\"rows\":[";
	for (size_t i = 0; i < result.rows.size(); i++) {
		if (i > 0) json << ",";
		json << "{";
		const std::map<std::string, std::string>& row = result.rows[i];

		// 使用传统迭代器替代auto
		std::map<std::string, std::string>::const_iterator it;
		size_t colIndex = 0;
		for (it = row.begin(); it != row.end(); ++it) {
			if (colIndex > 0) json << ",";
			json << "\"" << it->first << "\":\"" << it->second << "\"";
			colIndex++;
		}
		json << "}";
	}
	json << "]";
	json << "}";

	return json.str();
}

// ==================== JNI函数实现 ====================

// 创建DBConfig实例
JNIEXPORT jlong JNICALL Java_TelegrafDB_createInstance(JNIEnv* env, jobject obj, jstring filename) {
	try {
		std::string configFile = jstringToString(env, filename);
		DBConfig* dbConfig = new DBConfig(configFile);
		return reinterpret_cast<jlong>(dbConfig);
	} catch (...) {
		return 0;
	}
}

// 销毁实例
JNIEXPORT void JNICALL Java_TelegrafDB_destroyInstance(JNIEnv* env, jobject obj, jlong handle) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (dbConfig) {
		delete dbConfig;
	}
}

// 加载配置
JNIEXPORT void JNICALL Java_TelegrafDB_loadConfig(JNIEnv* env, jobject obj, jlong handle, jstring filename) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (dbConfig) {
		std::string configFile = jstringToString(env, filename);
		dbConfig->load(configFile);
	}
}

// 打印配置
JNIEXPORT void JNICALL Java_TelegrafDB_printConfig(JNIEnv* env, jobject obj, jlong handle) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (dbConfig) {
		dbConfig->print();
	}
}

// 时序数据库登录
JNIEXPORT jint JNICALL Java_TelegrafDB_login(JNIEnv* env, jobject obj, jlong handle) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	return dbConfig ? dbConfig->login() : DBCI_ERROR;
}

// 时序数据库插入
JNIEXPORT jint JNICALL Java_TelegrafDB_insertData(JNIEnv* env, jobject obj, jlong handle, jstring postData, jint mode) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return DBCI_ERROR;

	std::string data = jstringToString(env, postData);
	return dbConfig->insert(data, mode);
}

// 关系数据库连接
JNIEXPORT jint JNICALL Java_TelegrafDB_connectInitDB(JNIEnv* env, jobject obj, jlong handle, jstring database) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return DBConfig::CONNECTION_FAILED;

	std::string db = jstringToString(env, database);
	DBConfig::ConnectionStatus status = dbConfig->connectInitDB(db);
	return static_cast<jint>(status);
}

// 断开连接
JNIEXPORT void JNICALL Java_TelegrafDB_disconnectFromDB(JNIEnv* env, jobject obj, jlong handle) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (dbConfig) dbConfig->disconnectFromDB();
}

// 检查连接状态
JNIEXPORT jboolean JNICALL Java_TelegrafDB_isDBConnected(JNIEnv* env, jobject obj, jlong handle) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	return dbConfig ? (dbConfig->isDBConnected() ? JNI_TRUE : JNI_FALSE) : JNI_FALSE;
}

// 创建数据库
JNIEXPORT jboolean JNICALL Java_TelegrafDB_createDatabase(JNIEnv* env, jobject obj, jlong handle, jstring db_name) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return JNI_FALSE;

	std::string db = jstringToString(env, db_name);
	return dbConfig->createDatabase(db) ? JNI_TRUE : JNI_FALSE;
}

// 使用数据库
JNIEXPORT jboolean JNICALL Java_TelegrafDB_useDatabase(JNIEnv* env, jobject obj, jlong handle, jstring db_name) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return JNI_FALSE;

	std::string db = jstringToString(env, db_name);
	return dbConfig->useDatabase(db) ? JNI_TRUE : JNI_FALSE;
}

// 表是否存在
JNIEXPORT jboolean JNICALL Java_TelegrafDB_tableExists(JNIEnv* env, jobject obj, jlong handle, jstring table_name) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return JNI_FALSE;

	std::string table = jstringToString(env, table_name);
	return dbConfig->tableExists(table) ? JNI_TRUE : JNI_FALSE;
}

// 创建表
JNIEXPORT jboolean JNICALL Java_TelegrafDB_createTable(JNIEnv* env, jobject obj, jlong handle, jstring table_name, jobjectArray columns, jstring primary_key) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return JNI_FALSE;

	std::string table = jstringToString(env, table_name);
	std::vector<std::string> cols = jobjectArrayToStringVector(env, columns);
	std::string pk = jstringToString(env, primary_key);

	return dbConfig->createTable(table, cols, pk) ? JNI_TRUE : JNI_FALSE;
}

// 创建表（如果不存在）
JNIEXPORT jboolean JNICALL Java_TelegrafDB_createTableIfNotExists(JNIEnv* env, jobject obj, jlong handle, jstring table_name, jobjectArray columns, jstring primary_key) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return JNI_FALSE;

	std::string table = jstringToString(env, table_name);
	std::vector<std::string> cols = jobjectArrayToStringVector(env, columns);
	std::string pk = jstringToString(env, primary_key);

	return dbConfig->createTableIfNotExists(table, cols, pk) ? JNI_TRUE : JNI_FALSE;
}

// 删除表
JNIEXPORT jboolean JNICALL Java_TelegrafDB_dropTable(JNIEnv* env, jobject obj, jlong handle, jstring table_name) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return JNI_FALSE;

	std::string table = jstringToString(env, table_name);
	return dbConfig->dropTable(table) ? JNI_TRUE : JNI_FALSE;
}

// 插入数据（使用JSON格式）
JNIEXPORT jboolean JNICALL Java_TelegrafDB_insertToDB(JNIEnv* env, jobject obj, jlong handle, jstring table_name, jstring jsonData) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return JNI_FALSE;

	std::string table = jstringToString(env, table_name);
	std::string jsonStr = jstringToString(env, jsonData);

	std::map<std::string, std::string> data = jsonStringToMap(jsonStr);
	return dbConfig->insertToDB(table, data) ? JNI_TRUE : JNI_FALSE;
}

// 批量插入（使用JSON数组格式）
// 正确的实现
JNIEXPORT jboolean JNICALL Java_TelegrafDB_batchInsertToDB(JNIEnv* env, jobject obj, jlong handle, jstring table_name, jstring jsonArray) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return JNI_FALSE;

	std::string table = jstringToString(env, table_name);
	std::string jsonStr = jstringToString(env, jsonArray);

	std::vector<std::map<std::string, std::string>> dataList;

	// 调试输出
	std::cout << "=== 批量插入调试 ===" << std::endl;
	std::cout << "表名: " << table << std::endl;
	std::cout << "收到JSON数据长度: " << jsonStr.length() << std::endl;

	// 正确解析JSON数组
	if (jsonStr.length() > 2 && jsonStr[0] == '[' && jsonStr[jsonStr.length()-1] == ']') {
		// 移除外层的方括号
		std::string content = jsonStr.substr(1, jsonStr.length() - 2);

		size_t start = 0;
		size_t end = 0;
		int itemCount = 0;

		while (start < content.length()) {
			// 查找下一个对象开始位置
			start = content.find('{', end);
			if (start == std::string::npos) break;

			// 查找对象结束位置
			end = content.find('}', start);
			if (end == std::string::npos) break;

			// 提取单个JSON对象
			std::string itemStr = content.substr(start, end - start + 1);
			std::map<std::string, std::string> itemData = jsonStringToMap(itemStr);

			if (!itemData.empty()) {
				dataList.push_back(itemData);
				itemCount++;
			}

			end++; // 移动到下一个字符
			start = end;
		}

		std::cout << "解析出 " << itemCount << " 个数据对象" << std::endl;
	}

	if (dataList.empty()) {
		std::cout << "警告: 没有解析出任何数据记录" << std::endl;
		return JNI_FALSE;
	}

	// 执行批量插入
	bool result = dbConfig->batchInsertToDB(table, dataList);
	std::cout << "批量插入执行结果: " << (result ? "成功" : "失败") << std::endl;

	return result ? JNI_TRUE : JNI_FALSE;
}

// 执行查询（返回JSON格式）
JNIEXPORT jstring JNICALL Java_TelegrafDB_executeQuery(JNIEnv* env, jobject obj, jlong handle, jstring sql) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return env->NewStringUTF("{\"success\":false,\"error_message\":\"Invalid handle\"}");

	std::string sqlStr = jstringToString(env, sql);
	QueryResult result = dbConfig->executeQuery(sqlStr);

	std::string jsonResult = queryResultToJson(result);
	return stringToJString(env, jsonResult);
}

// 查询数据（返回JSON格式）
JNIEXPORT jstring JNICALL Java_TelegrafDB_selectFromDB(JNIEnv* env, jobject obj, jlong handle, jstring table_name, jobjectArray columns, jstring where_clause, jstring order_by, jint limit) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return env->NewStringUTF("{\"success\":false,\"error_message\":\"Invalid handle\"}");

	std::string table = jstringToString(env, table_name);
	std::vector<std::string> cols = jobjectArrayToStringVector(env, columns);
	std::string where = jstringToString(env, where_clause);
	std::string order = jstringToString(env, order_by);

	QueryResult result = dbConfig->selectFromDB(table, cols, where, order, limit);

	std::string jsonResult = queryResultToJson(result);
	return stringToJString(env, jsonResult);
}

// 执行SQL命令
JNIEXPORT jboolean JNICALL Java_TelegrafDB_executeCommand(JNIEnv* env, jobject obj, jlong handle, jstring sql) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return JNI_FALSE;

	std::string sqlStr = jstringToString(env, sql);
	return dbConfig->executeCommand(sqlStr) ? JNI_TRUE : JNI_FALSE;
}

// 获取行数
JNIEXPORT jint JNICALL Java_TelegrafDB_getRowCount(JNIEnv* env, jobject obj, jlong handle, jstring table_name, jstring where_clause) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return DBCI_ERROR;

	std::string table = jstringToString(env, table_name);
	std::string where = jstringToString(env, where_clause);

	return dbConfig->getRowCount(table, where);
}

// 获取最后错误信息
JNIEXPORT jstring JNICALL Java_TelegrafDB_getLastError(JNIEnv* env, jobject obj, jlong handle) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (!dbConfig) return env->NewStringUTF("Invalid handle");

	std::string error = dbConfig->getLastError();
	return stringToJString(env, error);
}

// 设置查询超时
JNIEXPORT void JNICALL Java_TelegrafDB_setQueryTimeout(JNIEnv* env, jobject obj, jlong handle, jint seconds) {
	DBConfig* dbConfig = reinterpret_cast<DBConfig*>(handle);
	if (dbConfig) {
		dbConfig->setQueryTimeout(seconds);
	}
}

#endif // TELEGRAF_JNI_EXPORT